<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Db;
use app\common\model\Wfdocument;
use app\common\model\Document;
use app\common\model\SearchLog;
class Wfgroup extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';

    public function index()
    {
        if($this->request->isAjax()){
            $page = $this->request->post('page',1);
            $size = $this->request->post('size',10);
            $keywords = $this->request->post('keywords','');
            $cate_id = $this->request->post('cate',0);
            $board = $this->request->post('board',0);
            $sort = $this->request->post('sort','');
            $start = $this->request->post('start','');
            $end =  $this->request->post('end','');

            $where = [];
            $orderBy = [];
            $where['d.status'] = 'normal';
            $where['d.is_audit'] = 1;
            if($keywords){
                $searchlog = SearchLog::get(['name'=>$keywords]);
                if(empty($searchlog)){
                    $searchlog = new Searchlog();
                    $searchlog->name = $keywords;
                    $searchlog->nums = 1;
                    
                }else{
                    $searchlog->nums = $searchlog['nums'] + 1;
                }
                $searchlog->save();
                $where['d.title|d.content'] = ['like','%'.$keywords.'%'];
            }
            if($board){
                $where['d.board'] = $board;
            }
            if($cate_id){
                $where['dc.wfcate_id'] = $cate_id;
            }
            if($sort){
                switch ($sort) {
                    case 'latest':
                        $orderBy['d.createtime'] = 'desc';
                        break;
                    case 'likes':
                        $orderBy['d.likes'] = 'desc';
                        break;
                    case 'comments':
                        $orderBy['d.comments'] = 'desc';
                        break;
                    case 'flags':
                        $orderBy['d.flags'] = 'desc';
                        break;
                    case 'latest_flags':
                        $orderBy['d.new_flag'] = 'desc';
                        break;
                    default:
                        $orderBy['d.createtime'] = 'desc';
                        break;
                }
            }
            if($start && $end){
             $where['d.createtime'] = ['between',[strtotime($start),strtotime($end." 23:59:59")]];
            }
            $weigh = '';
            foreach ($orderBy as $key => $value) {
                $weigh .= $key.' '.$value.',';
            }
            $weigh = rtrim($weigh,',');
            $list = Db::name('Wfdocument')->alias('d')->join('wd_wfdocument_category dc','dc.wfdocument_id = d.id')->where($where)
            ->order($weigh)->page($page,$size)->field('DISTINCT wfdocument_id,d.*')->select();
            foreach ($list as $key => &$value) {
                $value['createtime'] = date('Y-m-d H:i:s',$value['createtime']);
                $value['content'] = mb_substr(strip_tags($value['content']),0,200).'...';
                $user = Db::name('User')->where('id',$value['user_id'])->field('nickname,id,avatar,group_id')->find();
                $user['group_image'] = $user['group_id']?Db::name('UserGroup')->where('id','in',$user['group_id'])->select():[];
                $value['user'] = $user;
                $tag = [];
                if($value['board'] == 1){
                    $tag[] = ['name'=>'中榜']; 
                }
                if($value['board'] == 2){
                    $tag[] = ['name'=>'超级榜']; 
                }
                $value['tags'] =array_merge($tag ,  Db::name('WfdocumentCategory')->alias('dc')->join('wd_wfcate c', 'dc.wfcate_id = c.id')
                ->where('dc.wfdocument_id', $value['id'])->field('c.name')->select());
                $value['followlist'] = Db::name('DocumentUserFollow')->alias('d')->join('wd_user u','u.id=d.user_id')
                ->where('d.type','wf')->where('d.doc_id',$value['id'])->field('u.id,u.nickname,u.avatar')->limit(8)->select();
                $value['commonslist'] = Db::name('DocumentUserComments')->alias('d')->join('wd_user u','u.id=d.user_id')
                ->where('d.type','wf')->where('d.doc_id',$value['id'])->field('u.id,u.nickname,u.avatar,d.content,DATE_FORMAT(FROM_UNIXTIME(d.createtime), "%Y-%m-%d %H:%i") AS create_time')->limit(10)->select();
            }
            return json(['code'=>200,'data'=>$list,'msg'=>'success']);
        
        }
        $website = Db::name('Category')->where('url','/wfgroup')->find();
        $total = Db::name('Wfdocument')->where('status','normal')->count();
        $this->assign('total',$total);
        $this->assign('website',$website);
        return $this->view->fetch();
    }

    public function detail(){
        if($this->request->isAjax()){
            $id = $this->request->post('id',0);
            $where['id'] = $id;
            $data =Db::name('wfdocument')->where($where)->find();
            $data['createtime'] = date('Y-m-d H:i:s',$data['createtime']);
            $user = Db::name('User')->where('id',$data['user_id'])->field('nickname,id,avatar,group_id')->find();
            $user['group_image'] = $user['group_id']?Db::name('UserGroup')->where('id','in',$user['group_id'])->select():[];
            $user['doc'] =Db::name('Document')->where('user_id',$user['id'])->where('is_audit',1)->count('id');
            $user['featured'] =Db::name('Document')->where('user_id',$user['id'])->where('is_featured',1)->count('id');
            $user['attention'] =Db::name('UserAttention')->where('user_id',$user['id'])->count('id');
            $data['user'] = $user;
            $data['category'] = Db::name('Wdcate')->where('id',$data['wdcate_id'])->find();
            $tag = [];
                if($data['board'] == 1){
                    $tag[] = ['name'=>'中榜']; 
                }
                if($data['board'] == 2){
                    $tag[] = ['name'=>'超级榜']; 
                }
                $data['tags'] =array_merge($tag ,  Db::name('WfdocumentCategory')->alias('dc')->join('wd_wfcate c', 'dc.wfcate_id = c.id')
                ->where('dc.wfdocument_id', $data['id'])->field('c.name')->select());
            
            $data['followlist'] = Db::name('DocumentUserFollow')->alias('d')->join('wd_user u','u.id=d.user_id')
            ->where('d.type','wd')->where('d.doc_id',$data['id'])->field('u.id,u.nickname,u.avatar')->limit(8)->select();
            $data['commonslist'] = Db::name('DocumentUserComments')->alias('d')->join('wd_user u','u.id=d.user_id')
            ->where('d.type','wd')->where('d.doc_id',$data['id'])->field('u.id,u.nickname,u.avatar,d.content,DATE_FORMAT(FROM_UNIXTIME(d.createtime), "%Y-%m-%d %H:%i") AS create_time')->select();
            if($this->auth->id && $this->auth->level > 0){

            }else{
                $data['content'] = mb_substr(strip_tags($data['content']),0,200).'...';
            }
            return json(['code'=>200,'data'=>$data,'msg'=>'success']);
        
        }
        $id = $this->request->param('id');
        Db::name('Wfdocument')->where('id',$id)->setInc('clicks',1);
        Db::name('Document')->where('doc_id',$id)->where('type','wf')->setInc('clicks',1);
        Db::name('Wfdocument')->where('id',$id)->setInc('once_clicks',1);
        Db::name('Document')->where('doc_id',$id)->where('type','wf')->setInc('once_clicks',1);
        $this->assign('id',$id);
        return $this->view->fetch();
    }
    public function add(){
        if($this->request->isAjax()){
            
            $params = $this->request->post('row/a');
            Db::startTrans();
            try {
                $params['user_id'] = (int)$this->auth->id;
                $params['status'] = 'normal';
                $doc = Wfdocument::create($params,true);
                $docCate = [];
                foreach ($params['tags'] as $value) {
                    $docCate[] = ['wfdocument_id'=>$doc->id,'wfcate_id'=>$value];
                }
                Db::name('WfdocumentCategory')->insertAll($docCate);
                $document = $doc->toArray();
                $document['doc_id'] = $document['id'];
                unset($document['id']);
                unset($document['type_id']);
                $document['type'] = 'wf';
                Document::create($document,true);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success();   
        }
        $cate = Db::name('Wfcate')->where('status','normal')->column('name','id');
        $type = Db::name('Wftype')->where('status','normal')->column('name','id');
        $this->assign('cate',$cate);
        $this->assign('type',$type);
        return $this->view->fetch();
    }
}
